﻿using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using Plotly.Blazor;
using Plotly.Blazor.Interop;
using Plotly.Blazor.Traces;
using Plotly.Blazor.Traces.ScatterLib;
using System.Collections.Generic;

namespace BlazorSample.Pages
{
    public partial class PlotlyBlazorLiveChartTest : IDisposable
    {
        private PlotlyChart plotlyChart;
        private Plotly.Blazor.Layout layout;
        private bool ShowLiveChart = true;
        private Timer timer;
        private Config liveChartConfig = new Config();
        private Config staticChartConfig = new Config();

        // 实时图表数据（支持多条曲线）
        private List<ITrace> liveData = new List<ITrace>();
        private List<Scatter> liveTraces = new List<Scatter>();

        // 静态图表数据
        private List<ITrace> staticData = new List<ITrace>();
        private Scatter staticTrace = new Scatter();

        // 多条曲线的 X/Y 值缓存
        private List<List<object>> liveXSeries = new List<List<object>>();
        private List<List<object>> liveYSeries = new List<List<object>>();
        private List<object> staticXValues = new List<object>();
        private List<object> staticYValues = new List<object>();
        private Random random = new Random();
        private int dataCounter = 0;
        private const int MaxDataPoints = 50;
        private const int LiveSeriesCount = 3; // 可根据需要调整曲线数量

        protected override async Task OnInitializedAsync()
        {
            // 初始化布局
            layout = new Plotly.Blazor.Layout
            {
                Title = new Plotly.Blazor.LayoutLib.Title { Text = "实时数据图表" },
                XAxis = new List<Plotly.Blazor.LayoutLib.XAxis>
                {
                    new Plotly.Blazor.LayoutLib.XAxis {
                        Title = new Plotly.Blazor.LayoutLib.XAxisLib.Title
                        {
                            Text = "时间"
                        }
                    }
                },
                YAxis = new List<Plotly.Blazor.LayoutLib.YAxis>
                {
                    new Plotly.Blazor.LayoutLib.YAxis {
                        Title = new Plotly.Blazor.LayoutLib.YAxisLib.Title
                        {
                            Text = "数值"
                        }
                    }
                },
                Margin = new Plotly.Blazor.LayoutLib.Margin { L = 40, R = 30, T = 40, B = 40 }
            };

            liveChartConfig = new Config
            {
                Responsive = true,
            };

            staticChartConfig = new Config
            {
                Responsive = true,
            };

            // 生成初始静态数据
            GenerateStaticData();

            // 初始化实时数据结构（多条曲线）
            if (liveTraces.Count == 0)
            {
                for (int i = 0; i < LiveSeriesCount; i++)
                {
                    liveTraces.Add(new Scatter());
                    liveXSeries.Add(new List<object>());
                    liveYSeries.Add(new List<object>());
                }

                // 预置首批点，保证初次渲染有数据
                for (int i = 0; i < 10; i++)
                {
                    await AddLiveDataPoint();
                }
            }

            // 启动实时数据更新定时器
            StartLiveDataTimer();
        }

        protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            if (firstRender)
            {
                await jsRuntime.InvokeVoidAsync("import", "./plotlyInterop.js");
                await jsRuntime.InvokeVoidAsync("import", "./_content/Plotly.Blazor/plotly-3.0.0.min.js");
                await jsRuntime.InvokeVoidAsync("import", "./_content/Plotly.Blazor/plotly-interop-6.0.0.js");
            }
        }

        private void GenerateStaticData()
        {
            staticXValues.Clear();
            staticYValues.Clear();

            for (int i = 0; i < 50; i++)
            {
                staticXValues.Add(i);
                staticYValues.Add(Math.Sin(i * 0.5) * 10 + random.NextDouble() * 5);
            }

            staticTrace.X = staticXValues;
            staticTrace.Y = staticYValues;
            staticTrace.Mode = Plotly.Blazor.Traces.ScatterLib.ModeFlag.Lines | Plotly.Blazor.Traces.ScatterLib.ModeFlag.Markers;
            staticTrace.Name = "历史数据";
            staticTrace.Line = new Line { Color = "blue", Width = 2 };
            staticTrace.Marker = new Marker { Size = 6, Color = "blue" };

            staticData.Clear();
            staticData.Add(staticTrace);
        }

        private async Task AddLiveDataPoint()
        {
            // 为每条曲线生成并推送一个新点
            for (int i = 0; i < liveTraces.Count; i++)
            {
                var xList = liveXSeries[i];
                var yList = liveYSeries[i];

                var xVal = dataCounter;
                var yVal = Math.Sin((dataCounter + i) * 0.2) * 10 + (random.NextDouble() - 0.5) * 5 + i * 2;

                xList.Add(xVal);
                yList.Add(yVal);

                if (xList.Count > MaxDataPoints)
                {
                    xList.RemoveAt(0);
                    yList.RemoveAt(0);
                }

                // 初始化对应的 trace
                if (liveData.Count <= i)
                {
                    var trace = liveTraces[i];
                    trace.X = new List<object>(xList);
                    trace.Y = new List<object>(yList);
                    trace.Mode = Plotly.Blazor.Traces.ScatterLib.ModeFlag.Lines | Plotly.Blazor.Traces.ScatterLib.ModeFlag.Markers;
                    trace.Name = $"实时数据{i + 1}";
                    trace.Line = new Line { Color = i % 3 == 0 ? "red" : i % 3 == 1 ? "green" : "blue", Width = 2 };
                    trace.Marker = new Marker { Size = 6, Color = i % 3 == 0 ? "red" : i % 3 == 1 ? "green" : "blue" };
                    liveData.Add(trace);
                }
                else if (plotlyChart != null)
                {
                    // 对已存在的 trace 进行增量扩展
                    await plotlyChart.ExtendTrace(new List<object> { xVal }, new List<object> { yVal }, i);
                }
            }

            // 更新标题和计数器
            layout.Title.Text = $"实时数据图表 (最后更新: {DateTime.Now:HH:mm:ss})";
            dataCounter++;

            // 确保初次渲染完成
            if (liveData.Count == liveTraces.Count)
            {
                StateHasChanged();
            }
        }

        private void StartLiveDataTimer()
        {
            timer = new Timer(async _ =>
            {
                if (ShowLiveChart)
                {
                    await InvokeAsync(AddLiveDataPoint);
                }
            }, null, TimeSpan.Zero, TimeSpan.FromSeconds(1));
        }

        private void ToggleChartMode()
        {
            ShowLiveChart = !ShowLiveChart;

            if (ShowLiveChart)
            {
                layout.Title.Text = "实时数据图表";
                // 确保实时数据是最新的
                if (liveData.Count == 0)
                {
                    foreach (var trace in liveTraces)
                    {
                        liveData.Add(trace);
                    }
                }
            }
            else
            {
                layout.Title.Text = "历史数据图表";
                // 确保静态数据是最新的
                if (staticData.Count == 0)
                {
                    staticData.Add(staticTrace);
                }
            }

            StateHasChanged();
        }

        public void Dispose()
        {
            // 停止定时器
            timer?.Dispose();
        }
    }
}
